package com.example.chapter09.receiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

public class AlarmReceiver extends BroadcastReceiver {
    public static final String ALARM_ACTION = "com.example.chapter09.alarm";

    private final Context mContext;

    public AlarmReceiver(Context context) {
        super();
        this.mContext = context;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && intent.getAction().equals(ALARM_ACTION)) {
            Log.d("AlarmReceiver", "收到闹钟广播消息");
            // 循环发送闹钟广播
            sendAlarm();
        }
    }

    // 发送闹钟广播
    public void sendAlarm() {
        Intent intent = new Intent(ALARM_ACTION);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        AlarmManager manager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 1000, pendingIntent);
        } else {
            manager.set(AlarmManager.RTC_WAKEUP, 1000, pendingIntent);
        }
    }
}
